package com.svs.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.svs.common.base.AjaxResult;
import com.svs.common.utils.StringUtils;
import com.svs.framework.web.BackendController;

/**
 * 登录验证
 * 
 * @author dujianqiao
 */
@Controller
public class SysLoginController extends BackendController {
	
	@Value("${encryption.type}")
	private int encryptionType;
	
	@GetMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response,ModelMap mmap) {
//		// 如果是Ajax请求，返回Json字符串。
//		if (ServletUtils.isAjaxRequest(request)) {
//			return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
//		}
//		if(judgeIsMoblie(request)){
//			return "app_login";
//		}
		mmap.put("signType", encryptionType);
		String pcView = "login";
		String mView = "mobile/login";
		return goPage(pcView, mView);

	}
	
	public static boolean judgeIsMoblie(HttpServletRequest request) {
		boolean isMoblie = false;
		String[] mobileAgents = { "iphone", "android","ipad", "phone", "mobile", "wap", "netfront", "java", "opera mobi",
				"opera mini", "ucweb", "windows ce", "symbian", "series", "webos", "sony", "blackberry", "dopod",
				"nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma",
				"docomo", "up.browser", "up.link", "blazer", "helio", "hosin", "huawei", "novarra", "coolpad", "webos",
				"techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem",
				"wellcom", "bunjalloo", "maui", "smartphone", "iemobile", "spice", "bird", "zte-", "longcos",
				"pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320",
				"240x320", "176x220", "w3c ", "acs-", "alav", "alca", "amoi", "audi", "avan", "benq", "bird", "blac",
				"blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs",
				"kddi", "keji", "leno", "lg-c", "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi",
				"mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port",
				"prox", "qwap", "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem",
				"smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v",
				"voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-",
				"Googlebot-Mobile" };
		if (request.getHeader("User-Agent") != null) {
			String agent=request.getHeader("User-Agent");
			for (String mobileAgent : mobileAgents) {
				if (agent.toLowerCase().indexOf(mobileAgent) >= 0&&agent.toLowerCase().indexOf("windows nt")<=0 &&agent.toLowerCase().indexOf("macintosh")<=0) {
					isMoblie = true;
					break;
				}
			}
		}
		return isMoblie;
	}
	
//	@PostMapping(value={"/login"})
//	@ResponseBody
//	public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe) {
//		UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
//		Subject subject = SecurityUtils.getSubject();
//		try {
//			subject.login(token);
//			return success();
//		} catch (AuthenticationException e) {
//			String msg = "用户或密码错误";
//			if (StringUtils.isNotEmpty(e.getMessage())) {
//				msg = e.getMessage();
//			}
//			return error(msg);
//		}
//	}
	
	
	@ResponseBody
	@PostMapping(value={"/login"})
    public AjaxResult login(String username, String password, Boolean rememberMe) {
 
        JSONObject jsonObject = new JSONObject();
 
        Subject subject = SecurityUtils.getSubject();
 
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
 
        try {
            // 登录，即身份验证
        	subject.login(token);
        	jsonObject.put("error", 0);
        	jsonObject.put("msg", "登录成功");
        	// 返回sessionId作为token
        	jsonObject.put("token",subject.getSession().getId());
        } catch (AuthenticationException e) {
        	String msg = "用户或密码错误";
			if (StringUtils.isNotEmpty(e.getMessage())) {
				msg = e.getMessage();
			}
			return error(msg);
        }
        return AjaxResult.success(jsonObject.toString());
	}

	@GetMapping("/unauth")
	public String unauth() {
		return "/error/unauth";
	}
}
